/*课程首页*/
app.controller('CourseIndex', function($rootScope, $scope, $http, $location, $timeout, common, course, wechat){
    //变量声明
    $scope.course   = {list : new Array(), page : 0, is_end : false};
    $scope.cart     = {amount: 0, goods_type: 1, count: 0, list: {}};
    $scope.cate     = common.getUrlParam('cate', 1);

    //初始化JS
    $scope.init_js  = function(){
        var title   = $scope.cate == 1 ? '父母必修课' : '育儿急救站';
        common.setTitle(title);
        wechat.wxConfig();
    }
    //加载数据
    $scope.load_data    = function(){
        var object  = $scope.course;
        var page    = object.page + 1;
        var url     = config.prefix_url+'/Course/index?code='+config.code+
            '&page='+page+'&type=1&cate='+$scope.cate;
        if(object.is_end)   return true;

        $http.get(url).success(function(info){
            if(info.code != 1){
                common.dealError(info);
            }else{
                object.page     = page;
                object.is_end   = common.dealListInfo(info.data.list, object.list, page);
            }
            $('.load-more').html('加载更多');
        });
        
    }

    //购买课程
    $scope.buy_course   = function(courseId, courseInfo){
        if(courseInfo.price == 0){
            var callback    = function(){
                $scope.course.page  = 0;
                $scope.course.is_end = false;
                $scope.load_data();
            }
        }else{
            var callback    = function(){
                $timeout(function(){
                    $scope.course.page  = 0;
                    $scope.course.is_end = false;
                    $scope.load_data();
                }, 2000);
            }
        }

        course.buy_course(courseId, callback);
        // course.buy_course(courseId, function(){
        //     //支付成功回掉
        //     $timeout(function(){
        //         $scope.course.page  = 0;
        //         $scope.course.is_end = false;
        //         $scope.load_data();
        //     }, 2000);
        // });
    }
    
    //听课
    $scope.listen   = function(courseId, playType){
        course.listen(playType, courseId);
    }

    //课程详情
    $scope.detail   = function(courseId){
        S('detail_course_id', courseId);
        $location.path('/Course/detail');
    }

    //购物车操作
    $scope.cart_ops     = function(course, type){
        switch(type){
            case 'add':
                $scope.cart.list[course.id]     = course;
                $scope.cart.amount   += parseFloat(course.price);
                $scope.cart.count   += 1;
                course.in_cart     = 1;
            break;

            case 'minus':
                delete  $scope.cart.list[course.id];
                $scope.cart.amount   -= parseFloat(course.price);
                $scope.cart.count   -= 1;
                course.in_cart      = 0;
            break;
            defalut: break;
        }
        console.log($scope.cart);
    }

    //购物车结算
    $scope.cart_settle  = function(){
        S('shop_cart', $scope.cart);
        common.logAnchor();
        $location.path('/ShopCart/list');
    }

    $scope.load_data();
    $scope.init_js();
});

/*课程播放*/
app.controller('CoursePlayAudio', function($rootScope, $scope, $http, $location, $timeout, common, course, wechat){
    $scope.players  = new Array();
    $scope.hasBuy   = true;
    $scope.courseId     = S('play_course_id');
    $scope.chapterId    = S('play_chapter_id');
    $scope.leaveMsgList = [];

    if(!$scope.courseId)    return false;
    if(!$scope.chapterId)   $scope.chapterId    = 0;

    var $ppt    = $('.am-slider');
    var $loadJsPPT  = false;
    var $mask   = true;
    //PPT加载(轮播图)
    $scope.init_ppt     = function(){
        //设置标题
        common.setTitle('课程播放');
        //设置微信分享
        wechat.wxConfig();
        //初始化ppt
        $ppt.flexslider({
            slideshow:false,
            animationLoop:false,
            before  : function(){
                if($mask)   $scope.remove_mask();
            },
            after   : function(slider){
                $('.img-numb').html(slider.currentSlide+1);
            }
        });

        $loadJsPPT    = true;
    }

    //购买课程
    $scope.buy_course   = function(){
        course.buy_course($scope.courseId, function(){
            //支付成功回掉
            $timeout(function(){
                window.history.back();
            }, 2000);
        });
    }

    //加载课程数据
    $scope.load_data    = function(){
        var url     = config.prefix_url+'/Course/chapters?code='+config.code+
            '&course_id='+$scope.courseId;

        $http.get(url).success(function(info){
            if(info.code == 1){
                $scope.course   = info.data.course_info;
                //判断课程是否购买
                if($scope.course.buy_status != 1 && $scope.course.buy_status != 3){
                    $scope.hasBuy   = false;
                }
                $scope.leaveMsgList     = info.data.leavemsg_list;
                $scope.chapters     = info.data.chapter_list;
                //判断数据是否支持播放
                if($scope.chapters && $scope.init_audio($scope.chapters)){
                    //播放指定章节
                    var playNum     = 0;
                    if($scope.chapterId){
                        for(var i in $scope.chapters){
                            if($scope.chapterId == $scope.chapters[i].id){
                                playNum     = i;
                            }
                        }
                    }
                    $scope.play_chapter(playNum);

                    //蒙版展示
                    $('.ppt-guide').css('display', 'block');
                }else{
                    common.doAlert('该课程暂无可播放章节,请重试!');
                    window.history.back();
                    return false;
                }
            }else{
                common.dealError(info);
                window.history.back();
                return false;
            }
        });
    }

    //初始化音频
    $scope.init_audio   = function(chapters){
        var playCount  = 0;
        for(var k in chapters){
            var chapter     = chapters[k];
            if(chapter.can_listen){
                var audio   = $('<audio></audio>');
                audio.attr('src', chapter.audio);
                audio.attr('preload', 'none');
                if(chapter.id == $scope.chapterId){
                    audio.attr('autoplay', true);
                }
                $('.box-audio').append(audio);
                playCount++;
            }
        }
        $('audio').audioPlayer();
        // if(autoAudio)
        //     autoAudio.attr('autoplay', true);

        // $timeout(function(){
        //     //audio监听事件
        //     $('audio').each(function(index){
        //         var audio   = $(this)[0];
        //         var wrap    = $('.audioplayer').eq(index);
        //         audio.addEventListener('play', function(boolean){ 
        //             console.log('playing');
        //             wrap.addClass('audioplayer-playing');
        //         })
        //         audio.addEventListener('pause', function(boolean){
        //             console.log('pauseing');
        //             wrap.removeClass('audioplayer-playing');
        //         })
        //     });
        // }, 200);

        return playCount;
    }

    //播放课程
    $scope.play_chapter  = function(number){
        $scope.chapterIndex     = number;
        $scope.chapterImgs   = $scope.chapters[number]['imgs'];
        $scope.chapterAudio  = $scope.chapters[number]['audio'];
        $scope.chapterAttach    = $scope.chapters[number]['attach'];
        
        $scope.play_audio(number, $scope.chapters[number]);
        //记录观看历史
        var url     = config.prefix_url+'/Course/addWatchLog?code='+config.code;
        var param   = {
            'course_id' : $scope.courseId,
            'chapter_id': $scope.chapters[number]['id']
        }
        
        $http.post(url, param).success(function(info){
            console.log(info);
        });
        
        setTimeout(function(){
            $('.chapter-list').children('li').removeClass('active');
            $('.chapter-list').children('li').eq(number).addClass('active');
        }, config.dom_delay); 

        $scope.chapterId    = $scope.chapters[number]['id'];
        S('play_chapter_id', $scope.chapters[number]['id']);
    }

    //音乐播放
    $scope.play_audio   = function(number, chapter){
        $('.box-audio').find('audio').each(function(index){
            var wrap    = $(this).parent('.audioplayer');
            var audio   = $(this)[0];
            if(index != number){
                $(wrap).css('display', 'none');
                audio.pause();
                // $timeout(function(){
                //     audio.pause()
                // }, 200);
            }else{
                $(wrap).css('display', 'block');
                if(!chapter.is_load){
                    audio.load();
                    chapter.is_load     = 1;
                    audio.onloadedmetadata  = function(){
                        setTimeout(function(){
                            $(wrap).find('.audioplayer-time-duration').html(chapter.format_minute);
                        }, 500);
                    }
                }
                // $timeout(function(){
                //     audio.play();
                // }, 200)
            }
        });
    }

    //生成毕业证
    $scope.share_graduate    = function(){
        common.getUserInfo(function(user){
            var themeId     = D('share_graduate_theme_id') ? D('share_graduate_theme_id') : 1;
            var url     = 'index.html?'+
                '&param='+base64encode('user_id='+user.id+'&course_id='+$scope.courseId+'&theme_id='+themeId)+
                '&#/Share/graduate';
            window.open(url, '_self');
        });
    }

    //生成邀请码
    $scope.share_course     = function(){
        common.getUserInfo(function(user){
            var themeId = D('share_course_theme_id') ? D('share_course_theme_id') : 1;
            var url     = 'index.html?'+
                '&param='+base64encode('user_id='+user.id+'&course_id='+$scope.courseId+'&theme_id='+themeId)+
                '&#/Share/course';
            window.open(url, '_self');
        });
    }

    //移除ppt蒙版引导
    $scope.remove_mask  = function(){
        $('.ppt-guide').css('display' , 'none');
        $mask   = false;
    }

    //PPT变动监听
    $scope.$watch('chapterImgs', function(nVal, oVal, scope){
        if(!$loadJsPPT) return false;

        //清空原有PPT
        var pptCount    = $ppt.flexslider('count');
        for(var i = 0; i < pptCount; i++){
            $ppt.flexslider('removeSlide', 0);
        }

        //添加新ppt
        try{
            for(var i = 0; i < nVal.length; i++){
                $ppt.flexslider('addSlide', '<li><img src="'+nVal[i]+'"></li>');
            }
        }catch(e){}
    
        $ppt.flexslider(0);
    });

    //写留言
    $scope.write_leavemsg   = function(){
        common.writeLeaveMsg($scope.course.name, {
            'relate_type'   : 1,
            'relate_id' : $scope.courseId
        })
    }
    
    $scope.load_data();
    $scope.init_ppt();
});

//课程详情页
app.controller('CourseDetail', function($rootScope, $scope, $http, $location, common, course, wechat){
    //变量声明
    $scope.courseId   = S('detail_course_id');
    $scope.courseInfo   = {};
    $scope.leaveMsgList = [];

    if(!$scope.courseId){
        window.history.back();
        return false;
    }

    common.setTitle('课程详情');
    //微信分享设置(隐藏菜单)
    wechat.wxConfig();

    //加载信息
    $scope.load_data    = function(){
        var url     = config.prefix_url+'/Course/detail?code='+config.code+
            '&course_id='+$scope.courseId;
        $http.get(url).success(function(info){
            console.log(info);
            if(info.code != 1){
                common.dealError(info);
                return false;
            }
            $scope.courseInfo   = info.data.course_info;
            $scope.leaveMsgList = info.data.leavemsg_list;
            
        });
    }

    //试听课程
    $scope.try_listen   = function(courseId, playType){
        course.listen(playType, courseId);
    }

    //听课
    $scope.listen   = function(courseId, playType){
        course.listen(playType, courseId);
    }

    //购买课程
    $scope.buy_course   = function(courseId, courseInfo){
        if(courseInfo.price == 0){
            var callback    = function(){
                $scope.course.page  = 0;
                $scope.course.is_end = false;
                $scope.load_data();
            }
        }else{
            var callback    = function(){
                $timeout(function(){
                    $scope.course.page  = 0;
                    $scope.course.is_end = false;
                    $scope.load_data();
                }, 2000);
            }
        }

        course.buy_course(courseId, callback);
    }

    //写留言
    $scope.write_leavemsg   = function(){
        common.writeLeaveMsg($scope.courseInfo.name, {
            'relate_type'   : 1,
            'relate_id' : $scope.courseId
        })
    }

    $scope.load_data();
});

//免费课程列表获取
app.controller('CourseFree', function($rootScope, $scope, $http, $location, common, course, wechat){
    $scope.nPage    = 0;
    $scope.courses  = new Array();

    //初始化JS
    $scope.init_js  = function(){
        common.setTitle('免费试听');
        wechat.wxConfig();
    }
    //加载数据
    $scope.load_data    = function(){
        var page    = $scope.nPage + 1;
        var url     = config.prefix_url+'/Course/freeList?p='+page+'&code='+config.code;
        $http.get(url).success(function(info){
            console.log(info);
            if(info.code == 1){
                $scope.nPage    = page;
                var isEnd   = common.dealListInfo(info.data.list, $scope.courses, $scope.nPage);
                if(isEnd)
                    $('.load-more-a').css('display', 'none');
                console.log($scope.courses);
            }else{
                common.dealError(info);
            }
            $('.load-more-a').html('加载更多');
        });

        //提示‘加载中’
        $('.load-more-a').html('加载中...');
    }

    //课程详情
    $scope.detail   = function(courseId){
        //缓存当前课程ID
        console.log(courseId);
        S('now_course_id', courseId);
        //跳转免费课程详情页
        $location.path('Course/free_detail');
    }

    //听课
    $scope.listen   = function(courseId, playType){
        course.listen(playType, courseId);
    }

    $scope.load_data();
    $scope.init_js();
});

//免费课程详情页
app.controller('CourseFreeDetail', function($rootScope, $scope, $http, $location, common, course){
    $scope.courseId     = S('now_course_id');
    console.log($scope.courseId);
    if(!$scope.courseId){
        window.history.back();
    }

    //加载数据
    $scope.load_data    = function(){
        var url     = config.prefix_url+'/Course/detail?code='+config.code+
            '&course_id='+$scope.courseId;
        $http.get(url).success(function(info){
            console.log(info);
            if(info.code != 1){
                common.dealError(info);
            }else{
                $scope.courseInfo   = info.data.course_info;
            }
        });
    }

    //听课
    $scope.listen   = function(courseId, playType){
        course.listen(playType, courseId);
    }

    $scope.load_data();
});
